/**
 * 
 */
package org.gas.barapraja.handler;

import org.gas.barapraja.db.entity.Message;
import org.gas.barapraja.handler.validator.SingleMessageValidator;
import org.gas.barapraja.proc.MsgStore;
import org.gas.barapraja.proc.PduProcessor;
import org.gas.barapraja.proc.TemporaryMsgStore;

import com.logica.smpp.pdu.SubmitSM;
import com.logica.smpp.pdu.SubmitSMResp;
import com.logica.smpp.pdu.WrongLengthOfStringException;

/**
 * @author gilang
 *
 */
public class SingleMsgRequestHandler extends GasHandlerAdapter {

	private static SingleMsgComposer composer=new SingleMsgComposer();

	private MsgStore msgStore;

	private RequestValidator validator;
	
	private static long messageId=1;
	


	/**
	 * 
	 * @param pduProcessor
	 */
	public SingleMsgRequestHandler(PduProcessor pduProcessor) {
		setPduProcessor(pduProcessor);
		msgStore=TemporaryMsgStore.getInstance();
		validator=new SingleMessageValidator();
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.handler.GasHandlerAdapter#handleRequest(com.logica.smpp.pdu.SubmitSM)
	 */
	@Override
	public int handleRequest(SubmitSM submitSM) {
		int status=validator.validate(submitSM);
		try {
			if(status==GasValidatorAdapter.TOKEN_OK){
				Message message=composer.compose(submitSM);
				msgStore.addMsg(message);
				SubmitSMResp resp=(SubmitSMResp) submitSM.getResponse();
				resp.setMessageId(String.valueOf(messageId));
				pduProcessor.serverResponse(resp);
				messageId++;
			}
		} catch (WrongLengthOfStringException e) {
			e.printStackTrace();
		}
		return status;
	}



}

class SingleMsgComposer{

	public Message compose(SubmitSM sm){
		Message msg=new Message();
		msg.setSource(sm.getSourceAddr().getAddress());
 		msg.setTarget(sm.getDestAddr().getAddress());
		msg.setContent(sm.getShortMessage());
		return msg;
	}
}